package initialize

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/google/uuid"
	"github.com/hashicorp/consul/api"
	"github.com/nacos-group/nacos-sdk-go/clients"
	"github.com/nacos-group/nacos-sdk-go/common/constant"
	"github.com/nacos-group/nacos-sdk-go/vo"
	"github.com/spf13/viper"
	"go.uber.org/zap"
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials/insecure"
	"gopkg.in/yaml.v2"
	"net/http"
	"os"
	"os/signal"
	"syscall"
	"week_one/client/common/global"
	"week_one/client/routers"
	"week_one/client/vender/consul"
	user "week_one/user_srv/proto"
)

func init() {
	InitViper()
	InitNacos()
	InitZap()
	InitRouter()
}
func InitViper() {
	path := "./etc/dev.yaml"
	viper.SetConfigFile(path)
	err := viper.ReadInConfig()
	if err != nil {
		panic(err)
	}
	global.NacosConfig = &global.NaCosConf{
		Host:        viper.GetString("NacosConf.Host"),
		Port:        viper.GetInt("NacosConf.Port"),
		DataId:      viper.GetString("NacosConf.DataId"),
		Group:       viper.GetString("NacosConf.Group"),
		NamespaceId: viper.GetString("NacosConf.NamespaceId"),
	}
	fmt.Println(global.NacosConfig, "//")
}
func InitNacos() {
	// 创建clientConfig
	clientConfig := constant.ClientConfig{
		NamespaceId:         "", // 如果需要支持多namespace，我们可以场景多个client,它们有不同的NamespaceId。当namespace是public时，此处填空字符串。
		TimeoutMs:           5000,
		NotLoadCacheAtStart: true,
		LogLevel:            "debug",
	}
	// 至少一个ServerConfig
	serverConfigs := []constant.ServerConfig{
		{
			IpAddr: global.NacosConfig.Host,
			Port:   uint64(global.NacosConfig.Port),
		},
	}

	// 创建动态配置客户端的另一种方式 (推荐)
	configClient, err := clients.NewConfigClient(
		vo.NacosClientParam{
			ClientConfig:  &clientConfig,
			ServerConfigs: serverConfigs,
		},
	)
	if err != nil {
		panic(err)
	}
	content, err := configClient.GetConfig(vo.ConfigParam{
		DataId: global.NacosConfig.DataId,
		Group:  global.NacosConfig.Group,
	})
	if err != nil {
		panic(err)
	}
	yaml.Unmarshal([]byte(content), &global.ClientConfig)
	fmt.Println(global.ClientConfig.ApiConf, "==")
}
func InitZap() {
	config := zap.NewDevelopmentConfig()
	config.OutputPaths = []string{
		global.ClientConfig.ZapConf.LogUrl,
		global.ClientConfig.ZapConf.Stderr,
		global.ClientConfig.ZapConf.Stdout,
	}
	logger, _ := config.Build()
	zap.ReplaceGlobals(logger)
}
func InitWebServer() {
	server := &http.Server{
		Addr:    fmt.Sprintf("%s:%d", global.ClientConfig.ApiConf.Host, global.ClientConfig.ApiConf.Port),
		Handler: global.Router,
	}
	go func() {
		if err := server.ListenAndServe(); err != nil && err != http.ErrServerClosed {
			zap.S().Info("listen", zap.Error(err))
			panic(err)
		}
	}()
	consulClient := InitConsul()
	SigChan := make(chan os.Signal, 1)
	signal.Notify(SigChan, syscall.SIGTERM, syscall.SIGINT)
	<-SigChan
	//注销consul
	err := consulClient.Deregister(global.ClientConfig.ConsulConf.Id)
	if err != nil {
		panic(err)
	}
}
func InitConsul() consul.RegistryClient {
	var (
		err error
	)
	global.ConsulClient, err = api.NewClient(api.DefaultConfig())
	if err != nil {
		panic(err)
	}
	consulClient := consul.NewRegistryClient(global.ClientConfig.ApiConf.Host, global.ClientConfig.ApiConf.Port)
	//服务发现
	i := consulClient.AgentHealthServiceByName(global.ClientConfig.ConsulConf.UserConsulName)
	//拨号
	conn, err := grpc.Dial(fmt.Sprintf("%s:%d", i[0].Service.Address, i[0].Service.Port), grpc.WithBlock(), grpc.WithTransportCredentials(insecure.NewCredentials()))
	if err != nil {
		panic(err)
	}
	global.UserClient = user.NewUserClient(conn)
	//注册consul
	global.ClientConfig.ConsulConf.Id = uuid.NewString()
	err = consulClient.RegisterConsul(global.ClientConfig.ConsulConf.Id, global.ClientConfig.ConsulConf.Name, global.ClientConfig.ConsulConf.Tags)
	if err != nil {
		panic(err)
	}
	zap.S().Info("consul register success")
	return consulClient
}
func InitRouter() {
	global.Router = gin.New()
	Group := global.Router.Group("v1")
	routers.UserRouter(Group)
}
